import moment from "moment";
// import { delayDate } from "./index";
export async function printHtml(data) {
  try {
    let style = getStyle();
    let container = getContainer(data);
    document.body.appendChild(style);
    document.body.appendChild(container);
    const imgs = container.getElementsByClassName("preview--img");
    const promiseAll = [];
    const imgTotal = imgs.length;
    if (imgTotal > 0) {
      console.log("imgs", imgs);
      for (let i = 0; i < imgTotal; i++) {
        promiseAll[i] = new Promise((resolve) => {
          const img = imgs[i];
          img.onload = function () {
            //第i张加载完成
            resolve(img);
          };
        });
      }
      await Promise.all(promiseAll);
      window.print();
      return false;
    } else {
      window.print();
      return false;
    }
  } catch (err) {
    console.log(err);
  }
}
//通过iframe打印
export async function printHtml2(data, cb) {
  try {
    let hasiframe = window.document.getElementById("print-iframe");
    const document = window.document;
    if (hasiframe) {
      hasiframe.contentWindow.document.body.innerHTML = "";
    } else {
      hasiframe = document.createElement("IFRAME");
      hasiframe.setAttribute("id", "print-iframe");
      hasiframe.setAttribute(
        "style",
        "position:absolute;left:0px;top:0px;z-index:-1;display:flex"
      );
      document.body.appendChild(hasiframe);
    }
    //监听打印完成
    hasiframe.contentWindow.addEventListener('afterprint', () => {
      cb && cb();
    });
    const container = getContainer(data);
    hasiframe.contentWindow.document.body.appendChild(container);
    //const children = hasiframe.contentWindow.document.getElementsByTagName("body")[0].children[0].children
    const children =
      hasiframe.contentWindow.document.getElementsByClassName("break--page");
    console.log("---------children------", children);
    const pageHeight = 1700;
    for (let i = 0; i < children.length; i++) {
      let topPageNum = Math.ceil(children[i].offsetTop / pageHeight);
      let bottomPageNum = Math.ceil(
        (children[i].offsetTop + children[i].offsetHeight) / pageHeight
      );
      if (topPageNum !== bottomPageNum) {
        console.log("------需要换页------", children[i]);
        let divParent = children[i].parentNode;
        let newBlock = document.createElement("div");
        newBlock.style.background = "#fff";
        let _H = topPageNum * pageHeight - children[i].offsetTop;
        newBlock.style.height = _H + "px";
        divParent.insertBefore(newBlock, children[i]);
      }
    }
    const imgs =
      hasiframe.contentWindow.document.getElementsByClassName("preview--img");
    const promiseAll = [];
    const imgTotal = imgs.length;
    if (imgTotal > 0) {
      for (let i = 0; i < imgTotal; i++) {
        promiseAll[i] = new Promise((resolve) => {
          const img = imgs[i];
          img.onload = function () {
            //第i张加载完成
            resolve(img);
          };
        });
      }
      await Promise.all(promiseAll);
      hasiframe.contentWindow.print();
      return false;
    } else {
      hasiframe.contentWindow.print();
      return false;
    }
  } catch (err) {
    console.log(err);
    console.log(cb);
  }
}

export function cleanAfterPrint() {
  try {
    const container = document.getElementById("print-container");
    const style = document.getElementById("print-style");
    document.body.removeChild(style);
    document.body.removeChild(container);
  } catch (err) {
    console.log(err);
  }
}

export function cleanAfterPrint2(dom) {
  try {
    console.log(
      "%c [ 清除Print-iframe ]-87",
      "font-size:13px; background:pink; color:#bf2c9f;",
      dom
    );
    const hasiframe = window.document.getElementById("print-iframe");
    if (hasiframe) {
      window.document.body.removeChild(hasiframe);
    }
  } catch (err) {
    console.log(err);
  }
}

// 设置打印样式
function getStyle() {
  let styleContent = `#print-container {
        display: none;
    }
    @media print {
        body > :not(.print-container) {
            display: none;
        }
        html,
        body {
            display: block !important;
        }
        #print-container {
            display: block;
        }
    }`;
  let style = document.createElement("style");
  style.setAttribute("id", "print-style");
  style.innerHTML = styleContent;
  return style;
}
// 清空打印内容
function cleanPrint() {
  let div = document.getElementById("print-container");
  if (div) {
    document.querySelector("body").removeChild(div);
  }
}

// 新建DOM，将需要打印的内容填充到DOM
function getContainer(data) {
  try {
    cleanPrint();
    let container = document.createElement("div");
    container.setAttribute("id", "print-container");
    if (window.cusTomPrint) {
      const con = window.cusTomPrint(data, moment);
      container.innerHTML = con;
      return container;
    } else {
      let imgs = "";
      if (data.images.length > 0) {
        data.images.forEach((item, index) => {
          if (index === 8 || index === 9) {
            imgs += `<div
            class="preview--img-box"
            style="
              width: 330px;
              height: 185px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin: 120px 5px 5px 5px;
            "
          >
            <img
              src="${item.image}"
              alt=""
              class="preview--img"
              style="width: 100%; height: 100%; object-fit: cover"
            />
          </div>`;
          } else if (index === 18 || index === 19) {
            imgs += `<div
            class="preview--img-box"
            style="
              width: 330px;
              height: 185px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin: 80px 5px 5px 5px;
            "
          >
            <img
              src="${item.image}"
              alt=""
              class="preview--img"
              style="width: 100%; height: 100%; object-fit: cover"
            />
          </div>`;
          } else if (index === 28 || index === 29) {
            imgs += `<div
            class="preview--img-box"
            style="
              width: 330px;
              height: 185px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin: 80px 5px 5px 5px;
            "
          >
            <img
              src="${item.image}"
              alt=""
              class="preview--img"
              style="width: 100%; height: 100%; object-fit: cover"
            />
          </div>`;
          } else if (index === 38 || index === 39) {
            imgs += `<div
            class="preview--img-box"
            style="
              width: 330px;
              height: 185px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin: 80px 5px 5px 5px;
            "
          >
            <img
              src="${item.image}"
              alt=""
              class="preview--img"
              style="width: 100%; height: 100%; object-fit: cover"
            />
          </div>`;
          } else {
            imgs += `<div
            class="preview--img-box"
            style="
              width: 330px;
              height: 185px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin: 5px 5px;
            "
          >
            <img
              src="${item.image}"
              alt=""
              class="preview--img"
              style="width: 100%; height: 100%; object-fit: cover"
            />
          </div>`;
          }
        });
      }
      const con = `<div class="report--header" style="width: 100%">
            <div
              class="report--header--item"
              style="
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: end;
                height: 30px;
                line-height: 30px;
              "
            >
              <span class="report--header--sub" style="color: #000; font-size: 16px"
                >姓名:${data.name ? data.name : "--"}</span
              >
            </div>
            <div
            class="report--header--item"
            style="
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: end;
              height: 30px;
              line-height: 30px;
            "
          >
            <span class="report--header--sub" style="color: #000; font-size: 16px"
              >性别:${data.sex === 1 ? "男" : "女"}</span
            >
          </div>
          <div
          class="report--header--item"
          style="
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: end;
            height: 30px;
            line-height: 30px;
          "
        >
          <span class="report--header--sub" style="color: #000; font-size: 16px"
            >年龄:${data.year}</span
          >
        </div>
            <div
              class="report--header--item"
              style="
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: end;
                height:30px;
                line-height: 30px;
              "
            >
              <span class="report--header--sub" style="color: #000; font-size: 16px"
                >检查部位:${data.pos ? data.pos : "--"}</span
              >
            </div>
      
            <div
            class="report--header--item"
            style="
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: end;
              height: 30px;
              line-height:30px;
            "
          >
            <span class="report--header--sub" style="color: #000; font-size: 16px"
              >检查时间:${moment(data.createdAt).format(
                "YYYY-MM-DD HH:mm:ss"
              )}</span
            >
          </div>
          </div>
          <div
            class="report--img"
            style="
              width: 100%;
              min-height: 460px;
              border-top: 1px solid black;
              border-bottom: 1px solid black;
              margin-bottom: 30px;
              display: flex;
              flex-wrap: wrap;
            "
          >
              ${imgs}
          </div>
          <div class="report--word">
            <h2
              class="report--title1"
              style="text-decoration: underline; font-weight: bold"
            >
              临床申请检查内容:
            </h2>
            <p
              class="report--pos"
              style="text-decoration: underline; font-size: 18px"
            >
              ${data.pos ? data.pos : "--"}
            </p>
            <h3 class="report--title2" style="font-weight: bold">超声所见:</h3>
            <p class="report--con" style="text-indent: 25px">
                ${data.seen ? data.seen : "--"}
            </p>
            <h3 class="report--title2" style="font-weight: bold">
              超声提示:
            </h3>
            <p class="report--con" style="text-indent: 25px">
                ${data.tips ? data.tips : "--"}
            </p>
          </div>
          <div
            class="report--footer"
            style="
              display: flex;
              width: 100%;
              height: 80px;
              align-items: center;
              justify-content: end;
              color: #000;
              border-top: 1px solid #000;
              position: relative;
            "
          > 
            <span class="footer--sub--tips"      
            style="
            color: #000;
            position: absolute;
            left: 0px;
            top:5px;
            font-weight: bold;
          ">此报告为辅助诊断,仅供临床诊断参考.</span>
            <span class="footer--sub" style="color: #000">检查医生:</span>
            <div class="sign--box" style="min-width: 100px;height: 70%;display: flex;align-items: center;justify-content: center">
              <img src="${
                data.doc_sign
              }" alt="" style="height:63%;object-fit:contain;">
            </div>
            <span class="footer--sub" style="color: #000">送检医生:</span>
            <div class="sign--box" style="min-width: 100px;height: 70%;display: flex;align-items: center;justify-content: center">
              <img src="${
                data.pat_sign
              }" alt="" style="height:63%;object-fit:contain;">
            </div>
          </div>`;
      container.innerHTML = con;
      return container;
    }
  } catch (err) {
    console.log(err);
  }
}
